<template>
  <div class="login-container">
    <div class="login-box" :class="{ 'slide-in': showBox }">
      <div class="login-header">
        <img src="@/assets/logo.svg" alt="Logo" class="logo animate__animated animate__fadeIn" />
        <h2 class="animate__animated animate__fadeInUp">洗护服务商户端</h2>
      </div>

      <el-tabs v-model="activeTab" class="login-tabs animate__animated animate__fadeInUp">
        <el-tab-pane label="登录" name="login">
          <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
            @keyup.enter="handleLogin"
          >
            <el-form-item prop="phone">
              <el-input
                v-model="loginForm.phone"
                placeholder="请输入手机号"
                :prefix-icon="Phone"
                clearable
                @clear="loginForm.phone = ''"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                :prefix-icon="Lock"
                show-password
                @keyup.enter="handleLogin"
              />
            </el-form-item>
            <div class="form-options">
              <el-checkbox v-model="rememberMe">记住我</el-checkbox>
              <el-button type="primary" link @click="activeTab = 'reset'">
                忘记密码？
              </el-button>
            </div>
            <el-form-item>
              <el-button
                type="primary"
                class="login-button"
                :loading="loading"
                @click="handleLogin"
              >
                登录
              </el-button>
            </el-form-item>
            <div class="divider">
              <span>其他登录方式</span>
            </div>
            <div class="social-login">
              <el-tooltip content="微信登录" placement="top">
                <el-button circle @click="handleSocialLogin('wechat')">
                  <el-icon><ChatDotRound /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="支付宝登录" placement="top">
                <el-button circle @click="handleSocialLogin('alipay')">
                  <el-icon><Money /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="抖音登录" placement="top">
                <el-button circle @click="handleSocialLogin('douyin')">
                  <el-icon><VideoPlay /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
            <!-- 测试账号提示 -->
            <div class="test-accounts-tip">
              <el-alert
                title="测试账号"
                type="info"
                :closable="false"
                show-icon
              >
                <template #default>
                  <div class="test-accounts">
                    <p><strong>可用测试账号：</strong></p>
                    <div class="account-item">
                      <span class="account-label">管理员：</span>
                      <el-button size="small" text @click="fillTestAccount('admin', '123456')">
                        admin / 123456
                      </el-button>
                    </div>
                    <div class="account-item">
                      <span class="account-label">手机号：</span>
                      <el-button size="small" text @click="fillTestAccount('13900139000', '123456')">
                        13900139000 / 123456
                      </el-button>
                    </div>
                    <div class="account-item">
                      <span class="account-label">商户：</span>
                      <el-button size="small" text @click="fillTestAccount('merchant01', '123456')">
                        merchant01 / 123456
                      </el-button>
                    </div>
                  </div>
                </template>
              </el-alert>
            </div>
            <div class="form-footer">
              <el-button type="primary" link @click="activeTab = 'register'">
                注册商家账号
              </el-button>
            </div>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="注册" name="register">
          <el-form
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            class="register-form"
          >
            <el-form-item prop="phone">
              <el-input
                v-model="registerForm.phone"
                placeholder="请输入手机号"
                :prefix-icon="Phone"
                clearable
                @clear="registerForm.phone = ''"
              />
            </el-form-item>
            <el-form-item prop="verifyCode">
              <div class="verify-code-input">
                <el-input
                  v-model="registerForm.verifyCode"
                  placeholder="请输入验证码"
                  :prefix-icon="Key"
                  maxlength="6"
                />
                <el-button
                  type="primary"
                  :disabled="!!countdown"
                  @click="handleSendCode('register')"
                >
                  {{ countdown ? `${countdown}s后重试` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="请设置密码"
                :prefix-icon="Lock"
                show-password
              />
              <div class="password-strength" v-if="registerForm.password">
                <div class="strength-label">密码强度：</div>
                <div class="strength-bars">
                  <div
                    v-for="i in 3"
                    :key="i"
                    class="strength-bar"
                    :class="{ active: passwordStrength >= i }"
                  ></div>
                </div>
                <div class="strength-text">{{ strengthText }}</div>
              </div>
            </el-form-item>
            <el-form-item prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="请确认密码"
                :prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="registerForm.agreement">
                我已阅读并同意
                <el-button type="primary" link @click="showAgreement = true">
                  《商家入驻协议》
                </el-button>
              </el-checkbox>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                class="register-button"
                :loading="loading"
                :disabled="!registerForm.agreement"
                @click="handleRegister"
              >
                注册
              </el-button>
            </el-form-item>
            <div class="form-footer">
              <el-button type="primary" link @click="activeTab = 'login'">
                返回登录
              </el-button>
            </div>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="重置密码" name="reset">
          <el-form
            ref="resetFormRef"
            :model="resetForm"
            :rules="resetRules"
            class="reset-form"
          >
            <el-form-item prop="phone">
              <el-input
                v-model="resetForm.phone"
                placeholder="请输入手机号"
                :prefix-icon="Phone"
                clearable
                @clear="resetForm.phone = ''"
              />
            </el-form-item>
            <el-form-item prop="verifyCode">
              <div class="verify-code-input">
                <el-input
                  v-model="resetForm.verifyCode"
                  placeholder="请输入验证码"
                  :prefix-icon="Key"
                  maxlength="6"
                />
                <el-button
                  type="primary"
                  :disabled="!!countdown"
                  @click="handleSendCode('reset')"
                >
                  {{ countdown ? `${countdown}s后重试` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="resetForm.password"
                type="password"
                placeholder="请设置新密码"
                :prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            <el-form-item prop="confirmPassword">
              <el-input
                v-model="resetForm.confirmPassword"
                type="password"
                placeholder="请确认新密码"
                :prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                class="reset-button"
                :loading="loading"
                @click="handleResetPassword"
              >
                重置密码
              </el-button>
            </el-form-item>
            <div class="form-footer">
              <el-button type="primary" link @click="activeTab = 'login'">
                返回登录
              </el-button>
            </div>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 协议弹窗 -->
    <el-dialog
      v-model="showAgreement"
      title="商家入驻协议"
      width="600px"
      class="agreement-dialog"
    >
      <div class="agreement-content">
        <!-- 协议内容 -->
      </div>
      <template #footer>
        <el-button @click="showAgreement = false">关闭</el-button>
        <el-button type="primary" @click="handleAgree">同意并继续</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Phone,
  Lock,
  Key,
  ChatDotRound,
  Money,
  VideoPlay
} from '@element-plus/icons-vue'
import { login, register, sendVerifyCode, resetPassword } from '@/api/auth'
import 'animate.css'

const router = useRouter()
const route = useRoute()
const activeTab = ref('login')
const loading = ref(false)
const countdown = ref(0)
const showBox = ref(false)
const showAgreement = ref(false)
const rememberMe = ref(false)

// 登录表单
const loginFormRef = ref(null)
const loginForm = reactive({
  phone: '',
  password: ''
})

const loginRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ]
}

// 注册表单
const registerFormRef = ref(null)
const registerForm = reactive({
  phone: '',
  verifyCode: '',
  password: '',
  confirmPassword: '',
  agreement: false
})

// 密码强度计算
const passwordStrength = computed(() => {
  const password = registerForm.password
  if (!password) return 0
  
  let strength = 0
  if (password.length >= 8) strength++
  if (/[A-Z]/.test(password) && /[a-z]/.test(password)) strength++
  if (/\d/.test(password) && /[^A-Za-z0-9]/.test(password)) strength++
  
  return strength
})

const strengthText = computed(() => {
  const strength = passwordStrength.value
  return ['弱', '中', '强'][strength - 1] || ''
})

const registerRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请设置密码', trigger: 'blur' },
    { min: 8, message: '密码长度不能小于8位', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/,
      message: '密码必须包含大小写字母和数字',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 重置密码表单
const resetFormRef = ref(null)
const resetForm = reactive({
  phone: '',
  verifyCode: '',
  password: '',
  confirmPassword: ''
})

const resetRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请设置新密码', trigger: 'blur' },
    { min: 8, message: '密码长度不能小于8位', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/,
      message: '密码必须包含大小写字母和数字',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    loading.value = true
    
    const response = await login({
      username: loginForm.phone, // 后端期望username字段
      password: loginForm.password
    })

    console.log('登录响应:', response)

    // 后端返回格式: { code: 200, data: { token: "xxx", userInfo: {...} }, message: "登录成功" }
    if (response.code === 200 && response.data) {
      const { token, userInfo } = response.data

      // 保存token和用户信息
      localStorage.setItem('merchant_token', token)
      localStorage.setItem('merchant_info', JSON.stringify(userInfo))
      localStorage.setItem('merchant_status', 'approved') // 测试环境默认已审核

      // 记住我功能
      if (rememberMe.value) {
        localStorage.setItem('rememberedPhone', loginForm.phone)
      } else {
        localStorage.removeItem('rememberedPhone')
      }

      ElMessage.success(response.message || '登录成功')
      console.log('准备跳转到', route.query.redirect || '/main/dashboard')
      router.push(route.query.redirect || '/main/dashboard')
    } else {
      throw new Error(response.message || '登录失败')
    }
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error(error.message || '登录失败')
  } finally {
    loading.value = false
  }
}

// 注册
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    await registerFormRef.value.validate()
    if (!registerForm.agreement) {
      return ElMessage.warning('请阅读并同意商家入驻协议')
    }
    
    loading.value = true
    await register(registerForm)
    ElMessage.success('注册成功，请登录')
    activeTab.value = 'login'
    loginForm.phone = registerForm.phone
  } catch (error) {
    console.error('注册失败:', error)
    ElMessage.error(error.message || '注册失败')
  } finally {
    loading.value = false
  }
}

// 重置密码
const handleResetPassword = async () => {
  if (!resetFormRef.value) return
  
  try {
    await resetFormRef.value.validate()
    loading.value = true
    
    await resetPassword(resetForm)
    ElMessage.success('密码重置成功，请登录')
    activeTab.value = 'login'
    loginForm.phone = resetForm.phone
  } catch (error) {
    console.error('重置密码失败:', error)
    ElMessage.error(error.message || '重置密码失败')
  } finally {
    loading.value = false
  }
}

// 发送验证码
const handleSendCode = async (type) => {
  const phone = type === 'login' ? loginForm.phone :
    type === 'register' ? registerForm.phone : resetForm.phone
  
  if (!phone) {
    return ElMessage.warning('请先输入手机号')
  }
  
  if (!/^1[3-9]\d{9}$/.test(phone)) {
    return ElMessage.warning('请输入正确的手机号码')
  }
  
  try {
    await sendVerifyCode({ phone, type })
    ElMessage.success('验证码已发送')
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error(error.message || '发送验证码失败')
  }
}

// 第三方登录
const handleSocialLogin = async (type) => {
  try {
    // 调用第三方登录接口
    const { data } = await login({ type })
    localStorage.setItem('merchant_token', data.token)
    localStorage.setItem('merchant_info', JSON.stringify(data.userInfo))
    localStorage.setItem('merchant_status', 'approved')
    
    ElMessage.success('登录成功')
    router.push(route.query.redirect || '/main/goods')
  } catch (error) {
    console.error('第三方登录失败:', error)
    ElMessage.error(error.message || '第三方登录失败')
  }
}

// 同意协议
const handleAgree = () => {
  registerForm.agreement = true
  showAgreement.value = false
}

// 填充测试账号
const fillTestAccount = (username, password) => {
  loginForm.phone = username
  loginForm.password = password
  ElMessage.info('已填充测试账号，点击登录即可')
}

// 初始化
onMounted(() => {
  showBox.value = true
  const rememberedPhone = localStorage.getItem('rememberedPhone')
  if (rememberedPhone) {
    loginForm.phone = rememberedPhone
    rememberMe.value = true
  } else {
    // 开发环境默认填入测试账号
    if (import.meta.env.DEV) {
      loginForm.phone = 'demo'
      loginForm.password = '123456'
    }
  }
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  
  .login-box {
    width: 400px;
    padding: 40px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    opacity: 0;
    transform: translateY(20px);
    transition: all 0.3s ease;
    
    &.slide-in {
      opacity: 1;
      transform: translateY(0);
    }
    
    .login-header {
      text-align: center;
      margin-bottom: 30px;
      
      .logo {
        width: 80px;
        height: 80px;
        margin-bottom: 16px;
      }
      
      h2 {
        font-size: 24px;
        color: #303133;
        margin: 0;
      }
    }
    
    .login-tabs {
      :deep(.el-tabs__nav) {
        width: 100%;
        display: flex;
        
        .el-tabs__item {
          flex: 1;
          text-align: center;
        }
      }
    }
    
    .login-form,
    .register-form,
    .reset-form {
      margin-top: 20px;
      
      .form-options {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
      }
      
      .login-button,
      .register-button,
      .reset-button {
        width: 100%;
      }
      
      .form-footer {
        display: flex;
        justify-content: center;
        margin-top: 16px;
        
        /* 当有多个子元素时使用space-between */
        &:has(:nth-child(2)) {
          justify-content: space-between;
        }
      }
    }
    
    .verify-code-input {
      display: flex;
      gap: 12px;
      
      .el-input {
        flex: 1;
      }
      
      .el-button {
        width: 120px;
      }
    }
    
    .password-strength {
      margin-top: 8px;
      display: flex;
      align-items: center;
      gap: 8px;
      
      .strength-label {
        font-size: 12px;
        color: #606266;
      }
      
      .strength-bars {
        display: flex;
        gap: 4px;
        
        .strength-bar {
          width: 40px;
          height: 4px;
          background: #dcdfe6;
          border-radius: 2px;
          transition: all 0.3s ease;
          
          &.active {
            &:nth-child(1) { background: #f56c6c; }
            &:nth-child(2) { background: #e6a23c; }
            &:nth-child(3) { background: #67c23a; }
          }
        }
      }
      
      .strength-text {
        font-size: 12px;
        color: #606266;
      }
    }
    
    .divider {
      display: flex;
      align-items: center;
      margin: 20px 0;
      color: #909399;
      font-size: 12px;
      
      &::before,
      &::after {
        content: '';
        flex: 1;
        height: 1px;
        background: #dcdfe6;
      }
      
      span {
        padding: 0 12px;
      }
    }
    
    .social-login {
      display: flex;
      justify-content: center;
      gap: 24px;
      margin-bottom: 20px;
      
      .el-button {
        font-size: 20px;
        transition: all 0.3s ease;
        
        &:hover {
          transform: translateY(-2px);
        }
      }
    }
  }
}

.agreement-dialog {
  :deep(.el-dialog__body) {
    max-height: 60vh;
    overflow-y: auto;
  }
  
  .agreement-content {
    line-height: 1.6;
    color: #606266;
  }
}

/* 响应式布局 */
@media screen and (max-width: 576px) {
  .login-container {
    .login-box {
      width: 90%;
      padding: 20px;
    }
  }
}

/* 动画效果 */
.animate__animated {
  animation-duration: 0.5s;
}

.animate__fadeIn {
  animation-name: fadeIn;
}

.animate__fadeInUp {
  animation-name: fadeInUp;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>